//
//  Network+Cache.swift
//  XNetwork_Example
//
//  Created by x on 2024/8/11.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import XNetwork
import Moya
//import UIKit

extension Storable where Self: TargetType {
    private var cachedUrl: URL {
        guard let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last else {
            fatalError("Couldn't search cache's directory.")
        }
        return URL(fileURLWithPath: path)
    }
    
    public var allowsStorage: (Response) -> Bool {
        return { _ in true}
    }
    
    public func cachedResponse(for key: CachingKey) throws -> Response {
        print(md5Key(key))
        let data = try Data(contentsOf: md5Key(key))
        
        return Response(statusCode: 200, data: data)
    }
    
    public func storeCachedResponse(_ cachedResponse: Response, for key: CachingKey) throws {
        try cachedResponse.data.write(to: md5Key(key))
    }
    
    public func removeCachedResponse(for key: CachingKey) throws {
        try FileManager.default.removeItem(at: md5Key(key))
        
    }
    
    public func removeAllCachedResponses() throws {
        try FileManager.default.removeItem(at: cachedUrl)
    }
    
    private func md5Key(_ key: CachingKey) -> URL {
        return cachedUrl.appendingPathComponent(String(key.stringValue.hashValue))
    }
}
